package com.sita.bike.utils;

import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.utils.L;
import com.sita.friend.Constant;

/**
 * Created by hongyun on 2016/1/29.
 */
public class ImageManager {

    public static void loadImage(final ImageView imageView, final String imageUrl) {
        // first check memory cache
        Bitmap bitmap = AccountUtils.getUserAvatar(imageUrl);

        if (bitmap != null) {
            Log.d("ImageLoader", "in cache");
            imageView.setImageBitmap(bitmap);
            return;
        }

        ImageLoader.getInstance().loadImage(imageUrl, new SimpleImageLoadingListener() {
            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                L.d("get ok");
                if (loadedImage != null &&
                        imageView.getTag() != null &&
                        imageView.getTag().toString().equals(imageUri)) {
                    L.d("get right image");
                    // Resize the avatar picture
                    L.d("resize image");
                    try {
                        Bitmap bitmap = BitmapUtils.fitBitmap(loadedImage, Constant.AVATAR_IMAGE_SIZE);
                        imageView.setImageBitmap(bitmap);
                        L.d("add image into cache");
                        AccountUtils.addUserAvatar(imageUri,bitmap);
                    }catch (RuntimeException e){
                        L.e(e);
                    }

                }
            }

        });
    }
}
